const router = require('express').Router();
const fs = require('fs');
const archiver = require('archiver');
const path = require('path');

router.get('/', function (req, res) {
    const directoryPath = path.join(__dirname, '../public/image-result-cache');
    const zipPath = path.join(__dirname, '../public/image-result-cache.zip');

    // 创建一个输出流，将文件写入ZIP
    const output = fs.createWriteStream(zipPath);
    const archive = archiver('zip', { zlib: { level: 9 } });

    archive.pipe(output); // 将输出流连接到响应对象
    archive.directory(directoryPath, 'image-result-cache'); // 添加目录中的所有文件到ZIP
    archive.finalize(); // 完成ZIP并发送响应

    // 监听完成事件，发送响应并删除ZIP文件
    output.on('close', function () {
        res.download(zipPath, 'image-result-cache.zip', function (err) {
            if (err) {
                console.error('Download error:', err);
            }
            fs.unlinkSync(zipPath); // 删除ZIP文件
        });
    });
});

module.exports = router;
